package com.sky.service.impl;

import com.sky.mapper.ReportMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class WorkSpaceServiceImpl implements WorkSpaceService {
    @Autowired
    private ReportMapper reportMapper;

    /**
     * 获取营业数据
     */
    @Override
    public BusinessDataVO getBusinessData(List<LocalDate> dateList) {
//营业额
        List<Double> turnoverList = reportMapper.getTurnoverStatistics(dateList);
        double turnover = 0.0;
        for (Double t : turnoverList) {
            turnover += t;
        }
//订单有效数量
        List<Integer> validOrderCountList = reportMapper.getValidOrderCountList(dateList);
        int validOrderCount = 0;
        for (Integer i : validOrderCountList) {
            validOrderCount += i;
        }
//订单总数
        Integer totalOrderCount = reportMapper.getTotalOrderCount(dateList);
        //平均客单价
        Double unitPrice = 0.0;
        if (validOrderCount != 0) {
            unitPrice = turnover / validOrderCount;
        }
//新增用户数量
        List<Integer> newUserList = reportMapper.getNewUserStatistics(dateList);
        int newUsers = 0;
        for (Integer i : newUserList) {
            newUsers += i;
        }
//订单完成率
        double orderCompletionRate = 0.0;
        if (totalOrderCount != null && totalOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / (double) totalOrderCount;
            // 保留两位小数
            orderCompletionRate = new java.math.BigDecimal(orderCompletionRate)
                    .setScale(2, java.math.RoundingMode.HALF_UP)
                    .doubleValue();
        }

        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }

    /**
     * 获取套餐总览
     */
    @Override
    public SetmealOverViewVO getSetmealOverView() {
        return SetmealOverViewVO.builder()
                .sold(reportMapper.getSetmealSoldCount())
                .discontinued(reportMapper.getSetmealDiscontinuedCount())
                .build();
    }

    /**
     * 获取菜品总览
     */
    @Override
    public DishOverViewVO getDishOverView() {
        return DishOverViewVO.builder()
                .sold(reportMapper.getDishSoldCount())
                .discontinued(reportMapper.getDishDiscontinuedCount())
                .build();
    }

    /**
     * 获取订单总览
     */
    @Override
    public OrderOverViewVO getOrderOverView() {
        return reportMapper.getOrderOverView();
    }
}


